<template>
  <lay-container :fluid="true" style="padding: 10px">
    <lay-row space="10">
      <lay-col xs="24">
        <lay-card>
          <div class="header">
            <div class="cearch_box"></div>
            <div>
              <input
                type="file"
                id="fileUpload"
                ref="fileUploads"
                style="display: none"
                @change="handleImageUpload"
              />
              <lay-button
                class="btn"
                type="primary"
                size="sm"
                value="上传文件"
                @click="clickFile"
                v-if="httpUrls.includes('/Setting/DevicelistUpload')"
              >
                批量导入设备</lay-button
              >
            </div>
          </div>

          <lay-table
            v-model:selectedKeys="selectedKeys"
            id="id"
            :columns="columns"
            :dataSource="dataSource"
            :checkbox="checkbox"
            :default-toolbar="false"
            @row="rowClick"
          >
            <template v-slot:alter="{ data }">
              <lay-button
                size="sm"
                type="primary"
                v-if="httpUrls.includes('/Setting/InsertorUpdateDevice')"
                @click="editItem(data)"
                >编辑</lay-button
              >
              <lay-button
                size="sm"
                type="danger"
                v-if="httpUrls.includes('/Setting/DeleteDevice')"
                @click="delShebei(data)"
                >删除</lay-button
              >
            </template>
          </lay-table>

          <lay-page
            v-model="current"
            v-model:limit="limit"
            :pages="pages"
            :total="total"
            :show-limit="true"
            :show-skip="true"
            :show-count="true"
            :show-page="true"
            @change="changePage"
          ></lay-page>
        </lay-card>
      </lay-col>
    </lay-row>

    <lay-layer type="drawer" v-model="visible" title="编辑设备">
      <div>
        <lay-form :model="model" ref="layFormRefs" required>
          <lay-form-item label="原管理编号" prop="originalManagementNo">
            <lay-input v-model="model.originalManagementNo"></lay-input>
          </lay-form-item>
          <lay-form-item label="管理编号" prop="managementNo">
            <lay-input v-model="model.managementNo"></lay-input>
          </lay-form-item>
          <lay-form-item label="设备编号" prop="deviceNo">
            <lay-input v-model="model.deviceNo"></lay-input>
          </lay-form-item>
          <lay-form-item label="设备名称" prop="deviceName">
            <lay-input v-model="model.deviceName"></lay-input>
          </lay-form-item>
          <lay-form-item label="规格型号" prop="model">
            <lay-input v-model="model.model"></lay-input>
          </lay-form-item>
          <lay-form-item label="制造厂" prop="manufacturer">
            <lay-input v-model="model.manufacturer"></lay-input>
          </lay-form-item>
          <lay-form-item label="出厂编号" prop="manufacturingNo">
            <lay-input v-model="model.manufacturingNo"></lay-input>
          </lay-form-item>
          <lay-form-item label="出厂日期" prop="productionDate">
            <lay-input v-model="model.productionDate"></lay-input>
          </lay-form-item>
          <lay-form-item label="测量范围" prop="measuringRange">
            <lay-input v-model="model.measuringRange"></lay-input>
          </lay-form-item>
          <lay-form-item label="分度值" prop="graduationValue">
            <lay-input v-model="model.graduationValue"></lay-input>
          </lay-form-item>
          <lay-form-item label="精度等级" prop="accuracyClass">
            <lay-input v-model="model.accuracyClass"></lay-input>
          </lay-form-item>
          <lay-form-item label="数量" prop="number">
            <lay-input v-model="model.number"></lay-input>
          </lay-form-item>

          <lay-form-item>
            <lay-button @click="submitClick">提交</lay-button>
          </lay-form-item>
        </lay-form>
      </div>
    </lay-layer>
  </lay-container>
</template>
<script lang="ts">
import { defineComponent, ref, onMounted, reactive, toRefs } from "vue";
import { layer } from "@layui/layer-vue";
import {
  GetDeviceInfos,
  DeleteDevice,
  InsertorUpdateDevice,
} from "../../../api/module/user";
import { httpServer } from "../../../api/config";

export default defineComponent({
  setup() {
    const user: any = sessionStorage.getItem("userInfo");
    const userInfo: any = JSON.parse(user);

    onMounted(() => {
      if (data.httpUrls.includes("/Setting/GetDeviceInfos")) {
        getShebeList();
      }

      
    });
    const rowClick = (data: any) => {};

    let httpUrl: any = ref([]);
    let url: any = sessionStorage.getItem("httpUrl");
    httpUrl.value = JSON.parse(url);
    const data = reactive({
      httpUrls: httpUrl,
      url: httpServer,
      selectedKeys: "",
      title: "新增用户",
      checkbox: true,
      visible: false,
      time: "",
      systemType: sessionStorage.getItem("systemType"),
      current: 1,
      total: 50,
      pages: 0,
      curren: 10,
      limit: 10,
      model: {} as any,
      validateModel: {
        username: "",
        password: "",
        specialty: "1",
      } as any,
      columns: [],
      dataSource: [] as any,
    });

    const delShebei = (item: any) => {
      layer.confirm("确定删除该设备？", {
        btn: [
          {
            text: "确定",
            callback: async () => {
              const res: any = await DeleteDevice({
                deviceid: item.deviceId,
              });
              if (res.code === 200) {
                getShebeList();
                layer.closeAll();
              }
            },
          },
          {
            text: "取消",
            callback: async () => {
              layer.closeAll();
            },
          },
        ],
      });
    };

    const getShebeList = async () => {
      const res: any = await GetDeviceInfos({
        pageIndex: data.current,
        pagePerCount: data.limit,
        condition: "",
      });

      if (res.code == 200) {
        data.total = res.data.totalCount;
        // data.pages = res.data.pageIndex;
        // data.limit = res.data.pagePerCount;
        data.dataSource = res.data.datas;
        let arr: any = ref([]);
        arr = [
          {
            title: "序号",
            width: "60px",
            type: "number",
            fixed: "left",
          },
          {
            title: "原管理编号",
            key: "originalManagementNo",
            ellipsisTooltip: true,
          },
          {
            title: "管理编号",
            key: "managementNo",
            ellipsisTooltip: true,
          },
          {
            title: "设备编号",
            key: "deviceNo",
            ellipsisTooltip: true,
          },
          {
            title: "设备名称",
            key: "deviceName",
            ellipsisTooltip: true,
          },
          {
            title: "规格型号",
            key: "model",
            ellipsisTooltip: true,
          },
          {
            title: "制造厂",
            key: "manufacturer",
            ellipsisTooltip: true,
          },
          {
            title: "出厂编号",
            key: "manufacturingNo",
            ellipsisTooltip: true,
          },
          {
            title: "出厂日期",
            key: "productionDate",
            ellipsisTooltip: true,
          },
          {
            title: "测量范围",
            ellipsisTooltip: true,
            key: "measuringRange",
          },
          {
            title: "分度值",
            ellipsisTooltip: true,
            key: "graduationValue",
          },
          {
            title: "精度等级",
            key: "accuracyClass",
            ellipsisTooltip: true,
          },
          {
            title: "数量",
            key: "number",
            ellipsisTooltip: true,
          },
          {
            title: "操作",
            customSlot: "alter",
          },
        ]
        console.log('data.systemType ', data.systemType );
        // 交委委托
        // 交委删除管理编号，
        if (data.systemType == '1') {
          let indes = arr.findIndex((item: any) => {
            return item.key === 'managementNo'
          })
          arr.splice(indes, 1);
        } else {
          // 建委委托 
          // 建委删除设备编号这列
          let indes = arr.findIndex((item: any) => {
            return item.key === 'deviceNo'
          })
          arr.splice(indes, 1);
        }
        data.columns = arr;
      }
    };

    const changePage = (item: any) => {
      data.limit = item.limit;
      data.current = item.current;
      getShebeList();
    };

    const editItem = (item: any) => {
      data.model = {
        ...item,
      };
      data.visible = true;
    };

    const fileUploads: any = ref();
    const clickFile = () => {
      fileUploads.value.dispatchEvent(new MouseEvent("click"));
    };

    const handleImageUpload = (event: any) => {
      const files = event.target.files[0];
      const formData = new FormData();
      formData.append("formFile", files);
      fetch(data.url + "/Setting/DevicelistUpload", {
        method: "POST",
        body: formData,
        headers: {
          token: userInfo.token,
        },
      })
        .then((data: any) => {
          if (data.status == 200) {
            layer.msg("导入成功！", { icon: 1, time: 1000 });
            getShebeList();
          }
        })
        .catch((error) => {
          console.error(error);
        });
    };

    const layFormRefs = ref();
    const submitClick = function () {
      layFormRefs.value.validate((isValidate: any, model: any, errors: any) => {
        if (isValidate) {
          submitFrom();
        } else {
        }
      });
    };

    const submitFrom = async () => {
      const res: any = await InsertorUpdateDevice({
        ...data.model,
        systemType: userInfo.systemType,
      });
      if (res.code == 200) {
        data.visible = false;
        getShebeList();
      }
    };

    return {
      handleImageUpload,
      clickFile,
      ...toRefs(data),
      submitClick,
      rowClick,
      changePage,
      editItem,
      delShebei,
      fileUploads,
      layFormRefs,
    };
  },
});
</script>

<style lang="less" scoped>
.cearch_box {
  display: flex;
  align-items: center;
  margin-bottom: 8px;

  .w {
    width: 50%;
  }

  .btn {
    margin: 0 16px;
  }
}

.layui-form {
  margin-top: 26px;
  margin-right: 26px;
}
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}
</style>
